package de.roskenet.clou.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.faces.application.FacesMessage;  
import javax.faces.context.FacesContext;  
  
import org.apache.commons.dbcp.BasicDataSource;
import org.primefaces.event.FileUploadEvent;  
import org.primefaces.model.UploadedFile;  

public class OldFileUploadController {
 
	private BasicDataSource dataSource;
	
	private static final String SQL_INSERT_PAGE =
			"INSERT into clouelement(name, active, mimetype, content) VALUES (?,'true','image/jpeg',?)";
	
	public BasicDataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(BasicDataSource dataSource) {
		this.dataSource = dataSource;
	}

	public void handleFileUpload(FileUploadEvent event) { 
        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " wurde hochgeladen.");  
        FacesContext.getCurrentInstance().addMessage(null, msg);
        
        UploadedFile theFile = event.getFile();
        saveFile(theFile.getFileName(), theFile);
        
    }	
	
	protected void saveFile(String name, UploadedFile file) {
		
		Connection conn = null;
		PreparedStatement stmt = null;
//		byte[] fileBytes = file.getContents();
		
		try {
			conn = dataSource.getConnection();
			stmt = conn.prepareStatement(SQL_INSERT_PAGE);
			stmt.setString(1, name);
			stmt.setBytes(2, file.getContents());

			stmt.executeUpdate();
			// Wir hoffen einfach, dass alles gutgegangen ist! :-)
			stmt.close();
			conn.close();
        
		} catch (Exception sqle) {
			System.out.println("Something went wrong!");
			sqle.printStackTrace();
		}
	}
}
